﻿using Sidvall.UI.Dialogs;
using Sidvall.UI.Messaging;
using Sidvall.UI.ViewModels;
using System.Windows;
using System.Windows.Controls;

namespace Sidvall.UI.Wpf.Controls
{
    public partial class WebControl : UserControl
    {
        #region Public Members

        public event System.EventHandler CloseSelected;

        #region ButtonMargin

        public static readonly System.Windows.DependencyProperty ButtonMarginProperty = System.Windows.DependencyProperty.Register(nameof(ButtonMargin), typeof(Thickness), typeof(WebControl),
            new System.Windows.FrameworkPropertyMetadata(new Thickness(0, 8, 8, 8), System.Windows.FrameworkPropertyMetadataOptions.None, null, null, false, System.Windows.Data.UpdateSourceTrigger.PropertyChanged));
        public Thickness ButtonMargin
        {
            get
            {
                return (Thickness)GetValue(ButtonMarginProperty);
            }
            set
            {
                SetValue(ButtonMarginProperty, value);
            }
        }

        #endregion
        #region ButtonVisibility

        public static readonly DependencyProperty ButtonVisibilityProperty = DependencyProperty.Register("ButtonVisibility", typeof(Visibility), typeof(WebControl));
        public Visibility ButtonVisibility
        {
            get
            {
                return (Visibility)GetValue(ButtonVisibilityProperty);
            }
            set
            {
                SetValue(ButtonVisibilityProperty, value);
            }
        }

        #endregion
        #region HtmlSource

        public static readonly DependencyProperty HtmlSourceProperty = DependencyProperty.Register("HtmlSource", typeof(string), typeof(WebControl));
        public string HtmlSource
        {
            get
            {
                return (string)GetValue(HtmlSourceProperty);
            }
            set
            {
                SetValue(HtmlSourceProperty, value);
            }
        }

        #endregion
        #region HtmlText

        public static readonly DependencyProperty HtmlTextProperty = DependencyProperty.Register("HtmlText", typeof(string), typeof(WebControl));
        public string HtmlText
        {
            get
            {
                return (string)GetValue(HtmlTextProperty);
            }
            set
            {
                SetValue(HtmlTextProperty, value);
            }
        }

        #endregion
        #region HttpRequestMessage

        public static readonly DependencyProperty HttpRequestMessageProperty = DependencyProperty.Register("HttpRequestMessage", typeof(Sidvall.Net.HttpRequestMessage), typeof(WebControl));
        public Sidvall.Net.HttpRequestMessage HttpRequestMessage
        {
            get
            {
                return (Sidvall.Net.HttpRequestMessage)GetValue(HttpRequestMessageProperty);
            }
            set
            {
                SetValue(HttpRequestMessageProperty, value);
            }
        }

        #endregion
        #region ViewModel

        public WebControlViewModel ViewModel
        {
            get
            {
                return this.DataContext as WebControlViewModel;
            }
            set
            {
                var oldValue = this.DataContext as WebControlViewModel;
                if (oldValue != null)
                    oldValue.CloseSelected -= OnCloseSelected;
                this.DataContext = value;
                if (value != null)
                    value.CloseSelected += OnCloseSelected;
            }
        }

        #endregion

        #region InitializeContext

        public void InitializeContext(WebDialogContext context)
        {
            if (context == null)
                throw new System.ArgumentNullException("context");
            var item = new WebControlViewModel()
            {
            };
            this.ViewModel = item;
            if (!string.IsNullOrWhiteSpace(context.RequestMessage?.WebAddress))
            {
                if (context.RequestMessage.Headers != null)
                    this.WebView.Navigate(new System.Uri(context.RequestMessage.WebAddress), null, null, context.RequestMessage.Headers.ToString() + "\r\n");
                else
                    this.WebView.Navigate(new System.Uri(context.RequestMessage.WebAddress));
            }
            else if (!string.IsNullOrWhiteSpace(context.HtmlText))
            {
                this.WebView.NavigateToString(context.HtmlText);
            }
        }

        #endregion
        #region OnPropertyChanged

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == ButtonVisibilityProperty)
            {
                this.ButtonControl.Visibility = this.ButtonVisibility;
            }
            else if (e.Property == HtmlSourceProperty)
            {
                if (!string.IsNullOrEmpty(this.HtmlSource))
                {
                    this.WebView.Navigate(new System.Uri(this.HtmlSource));
                }
            }
            else if (e.Property == HtmlTextProperty)
            {
                if (!string.IsNullOrEmpty(this.HtmlText))
                {
                    this.WebView.NavigateToString(this.HtmlText);
                }
            }
            else if (e.Property == HttpRequestMessageProperty)
            {
                if (!string.IsNullOrEmpty(this.HttpRequestMessage?.WebAddress))
                {
                    if (this.HttpRequestMessage.Headers != null)
                        this.WebView.Navigate(new System.Uri(this.HttpRequestMessage.WebAddress), null, null, this.HttpRequestMessage.Headers.ToString() + "\r\n");
                    else
                        this.WebView.Navigate(new System.Uri(this.HttpRequestMessage.WebAddress));
                }
            }
        }

        #endregion

        #endregion
        #region Private Members

        private WebBrowserManager WebBrowserManager { get; set; }
        private ControlViewModelBase ParentControl { get; set; }
        #region OnCloseSelected

        private void OnCloseSelected()
        {
            OnCloseSelected(new System.EventArgs());
        }
        private void OnCloseSelected(System.EventArgs args)
        {
            OnCloseSelected(this, args);
        }
        private void OnCloseSelected(object sender, System.EventArgs args)
        {
            if (this.CloseSelected != null)
                this.CloseSelected.Invoke(sender, args);
        }

        #endregion

        #endregion
        #region Events

        private void WebView_Loaded(object sender, RoutedEventArgs e)
        {
            if (Sidvall.UI.SystemContext.Current.DialogManager != null)
            {
                Sidvall.UI.SystemContext.Current.DialogManager.DialogOpening += DialogManager_DialogOpening;
                Sidvall.UI.SystemContext.Current.DialogManager.DialogClosing += DialogManager_DialogClosing;
            }
            var window = WindowManager.GetWindow(this);
            this.ParentControl = window?.DataContext as ControlViewModelBase;
            if (this.ParentControl != null)
            {
                this.ParentControl.IsBusyChanged += ParentControl_IsBusyChanged;
            }
        }
        private void WebView_Unloaded(object sender, RoutedEventArgs e)
        {
            if (Sidvall.UI.SystemContext.Current.DialogManager != null)
            {
                Sidvall.UI.SystemContext.Current.DialogManager.DialogOpening -= DialogManager_DialogOpening;
                Sidvall.UI.SystemContext.Current.DialogManager.DialogClosing -= DialogManager_DialogClosing;
            }
            if (this.ParentControl != null)
            {
                this.ParentControl.IsBusyChanged -= ParentControl_IsBusyChanged;
                this.ParentControl = null;
            }
        }

        void DialogManager_DialogOpening(object sender, Sidvall.UI.Dialogs.DialogEventArgs e)
        {
            this.WebBrowserManager.Hide();
        }
        void DialogManager_DialogClosing(object sender, Sidvall.UI.Dialogs.DialogEventArgs e)
        {
            this.WebBrowserManager.Show();
        }
        private void ParentControl_IsBusyChanged(object sender, BusyChangedEventArgs e)
        {
            if (e.IsBusy)
                this.WebBrowserManager.Hide();
            else
                this.WebBrowserManager.Show();
        }

        #endregion
        #region Constructors

        public WebControl()
        {
            InitializeComponent();
            this.WebBrowserManager = new WebBrowserManager(this.WebView);
        }

        #endregion
    }
}
